package open

import (
	"context"
	"log"
	"sync"

	v1 "mini-admin/internal/open/service/v1"

	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/transport/grpc"
)

var (
	once   sync.Once
	client v1.OpenServiceClient
)

// NewClient 新开放平台客户端
func NewClient(target string) v1.OpenServiceClient {
	conn, err := grpc.DialInsecure(
		context.Background(),
		grpc.WithEndpoint(target),
		grpc.WithMiddleware(
			middleware.Chain(
				recovery.Recovery(),
			),
		),
	)
	if err != nil {
		log.Fatal(err)
	}
	return v1.NewOpenServiceClient(conn)
}

// New 新建客户端
func New(target string) v1.OpenServiceClient {
	once.Do(func() {
		client = NewClient(target)
	})
	return client
}
